package com.web44.ssm.web;

import com.web44.ssm.bean.Adminuser;
import com.web44.ssm.service.impl.AdminuserService;
import com.web44.ssm.utils.ResponseVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Title: AdminuserController
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/2/18 11:06
 */
@RestController
@RequestMapping("adminuser")
public class AdminuserController {

    @Autowired
    private AdminuserService adminuserService;

    @GetMapping("test")
    @ResponseBody
    public ResponseVo testWeb() {
        System.out.println(1/0);
        return ResponseVo.ok("登录成功！");

    }

    @PostMapping("login")
    public ResponseVo adminLoginWeb(@RequestBody Adminuser adminuser) {
        String username = adminuser.getUsername();
        String password = adminuser.getPassword();
        // 获取shiro实体
        Subject subject = SecurityUtils.getSubject();
        // 获取token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        subject.login(token); // 进入到reaml中
        // 如果没有异常的话 会进入到这里  获取用户信息就可以了
        String uname = token.getPrincipal().toString();

        Adminuser user = adminuserService.queryAdminuserByUsername(uname);
        // 将用户存储到shio的session中
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("user",user);
        return ResponseVo.ok("登录成功",user);

    }

    /**
     * 获取当前登录的用户信息
     * @return
     */
    @GetMapping("current")
    public ResponseVo adminCurrentWeb() {
        String username = (String)SecurityUtils.getSubject().getPrincipal();
        Session session = SecurityUtils.getSubject().getSession();
        Adminuser user = (Adminuser)session.getAttribute("user");

        return ResponseVo.ok("获取用户成功！",user);

    }

//    @PostMapping("login")
//    public ResponseVo adminLoginWeb(@RequestBody Adminuser adminuser) {
//        String username = adminuser.getUsername();
//        String password = adminuser.getPassword();
//        Adminuser adminuser1 = adminuserService.queryAdminuserByUsername(username);
//        if(adminuser1 == null) {
//            throw  new RuntimeException("用户不存在！");
//        }
//        if(!adminuser1.getPassword().equals(password)) {
//            throw  new RuntimeException("密码错误！");
//        }
//
//        return ResponseVo.ok("登录成功！",adminuser1);
//
//
//
//    }
}
